package userModule.controller;

import userModule.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryUsersServlet", value = "/queryUsers")
public class QueryUsersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UserService userService = new UserService();

        //初始化(第一次进入此页面的时候给定的 当前的页码和每页显示的条数 的初始值)
        //默认第一页，每页3条数据
        int currentPageNumber = 1;
        int dataCountPerPage = 3;

        //第二次开始是从页面访问此servlet，所以当前的页码和每页显示的条数都必须从页面动态获取
        String currentPageNumberStr = request.getParameter("currentPageNumber");
        String dataCountPerPageStr = request.getParameter("dataCountPerPage");

        //如果是第二次从页面访问的情况下，也就是从页面获取的数据不为空的时候，转成int类型，且覆盖掉默认的值
        if(null!=currentPageNumberStr && !currentPageNumberStr.equals("")){
            currentPageNumber = Integer.parseInt(currentPageNumberStr);
        }
        if(null!=dataCountPerPageStr && !dataCountPerPageStr.equals("")){
            dataCountPerPage = Integer.parseInt(dataCountPerPageStr);
        }

        //调用dao层获取所有用户数据，并获得数据的总量
        int allUsersCount = userService.selectUsers().size();

        //把所有用户数据向上转型成double类型，目的是为了总页数的时候可以向上取整
        double allUsersCountDouble = allUsersCount;
        //通过用户总量除以每页的数量获取总页数
        int pageCount = (int)Math.ceil(allUsersCountDouble/dataCountPerPage);


        //调用dao层获取当前页的用户数据
        List<Map<String,Object>> currentPageUsersList = userService.selectUsers(currentPageNumber,dataCountPerPage);

        //获取当前的session，用于存储一些数据，方便页面展示
        HttpSession session = request.getSession();
        session.setAttribute("currentPageNumber",currentPageNumber);
        session.setAttribute("dataCountPerPage",dataCountPerPage);
        session.setAttribute("pageCount",pageCount);

        request.setAttribute("currentPageUsersList",currentPageUsersList);

        //携带以上数据转发到用户列表页面
        request.getRequestDispatcher("/jsp/userList.jsp").forward(request,response);


    }
}
